package cn.tedu.charging.order.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws/server/{userId}")
public class WebSocketServer {
    private static ConcurrentHashMap<Integer, Session> sessions = new ConcurrentHashMap<Integer,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        sessions.put(userId, session);
        log.info("用户:{},连接成功:{}", userId, session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.debug("用户:{},发送消息:{}",session,message);
    }

    public void sendMessage(Integer userId, String message) {
        Session session = sessions.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else {
            log.error("用户:{},已经下线",userId);
        }
    }

    @OnClose
    public void onClose(Session session,@PathParam("userId") Integer userId){
        sessions.remove(userId);
    }

    @OnError
    public void onError(Session session,Throwable throwable) {
        log.error("error",throwable);
    }
}
